package com.kltn.zigo;

import java.util.ArrayList;
import java.util.HashMap;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.kltn.zigo.data.adapter.PlaceMapAdapter;
import com.kltn.zigo.data.loader.PlaceMapLoader;

import android.app.ActionBar;import android.app.ProgressDialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

@SuppressLint("NewApi")
public class NearHereActivity extends FragmentActivity implements OnMyLocationChangeListener, OnInfoWindowClickListener {
	// Google Map
    private GoogleMap googleMap;
    /*private Circle circle;
    private Marker marker;
    private LocationClient mLocationClient;*/
    
    private Button btnLocation;
    private Button btnNewPost;
	private ProgressDialog pDialog;
	PlaceMapAdapter adapter;	
	Location localLocation;
    //JSONParser jParser = new JSONParser();
    private static LayoutInflater inflater=null;
    String placeIdClicked = "";

	// Progress Dialog
	//private ProgressDialog pDialog;

    private ArrayList<HashMap<String, String>> data;
    private HashMap<Marker, String> listMarker;
    
	ListView list;
	//EditText inputSearch;
	//PlaceAdapter adapter;
	
	String userid;
	String username;
	String userdisplayname;
	String useravatarurl;
	
    private MenuItem btnMenu;
    private MenuItem btnSearch;
    private MenuItem btnProfile;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_near_here);
		ActionBar actionBar = getActionBar();		
		actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#b51d21")));
		btnLocation = (Button) findViewById(R.id.btnOkLoc);
		btnNewPost = (Button) findViewById(R.id.btnNewPost);
		list = (ListView) findViewById(R.id.list_places);
		listMarker = new HashMap<Marker,String>();
		
		userid = getIntent().getStringExtra("userid");
		username = getIntent().getStringExtra("username");
		userdisplayname = getIntent().getStringExtra("userdisplayname");
		useravatarurl = getIntent().getStringExtra("useravatarurl");
		
		try {
            // Loading map
            //initilizeMap();
			if (googleMap == null) {
	            googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
	 
	            // check if map is created successfully or not
	            if (googleMap == null) {
	                Toast.makeText(getApplicationContext(),
	                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
	                        .show();
	            }
	            else
	            {
					
	            	googleMap.setMyLocationEnabled(true);
	            	googleMap.setOnMyLocationChangeListener(this);  
	            	googleMap.setOnInfoWindowClickListener(this);
	        		new LoadPlaceAsync().execute();
	            }
	        }			
 
        } catch (Exception e) {
            e.printStackTrace();
        }
		
		btnNewPost.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
		    	Intent i=new Intent(getApplicationContext(),NewPostActivity.class);
		        i.putExtra("userid", userid);
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", userdisplayname);
		        i.putExtra("useravatarurl", useravatarurl);
			    startActivity(i);
			}
		});
		
		list.setOnItemClickListener(new OnItemClickListener() {
        	@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {							
        		View vi=view;
		        if(view==null)
		            vi = inflater.inflate(R.layout.item_list_place, null);

		        TextView placeID = (TextView)vi.findViewById(R.id.tvID);
		        
		        placeIdClicked = placeID.getText().toString();
		        
		        Intent i=new Intent(NearHereActivity.this,PlaceDetailActivity.class);
		        i.putExtra("placeid", placeIdClicked);
		        i.putExtra("userid",userid);
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", userdisplayname);
		        i.putExtra("useravatarurl", useravatarurl);
			    startActivity(i);
			}
		});
		
		/*if(googleMap.getMyLocation() != null){
			new LoadPlaceAsync().execute();
		}*/
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.near_here, menu);
		btnMenu = menu.findItem(R.id.btn_menu);
		btnSearch = menu.findItem(R.id.btn_search);
		btnProfile = menu.findItem(R.id.btn_profile);
		
		return true;
	}
	
	@Override
	  public boolean onOptionsItemSelected(MenuItem item) {
		 switch (item.getItemId()) {
		   
		    case R.id.btn_profile:
		    {
		    	Intent i=new Intent(getApplicationContext(),ProfileUserActivity.class);
		        i.putExtra("userid", userid);
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", userdisplayname);
		        i.putExtra("useravatarurl", useravatarurl);
			    startActivity(i);
		    	break;
		    }
		    	
		    case R.id.btn_search:
		    {
		    	Intent i=new Intent(getApplicationContext(),ListPlaceActivity.class);
		    	i.putExtra("userid",userid);
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", userdisplayname);
		        i.putExtra("useravatarurl", useravatarurl);
			    startActivity(i);
			    break;
		    }
		    
		    case R.id.btn_menu:
		    {
		    	Intent i=new Intent(getApplicationContext(),MainActivity.class);
		        i.putExtra("userid", userid);
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", userdisplayname);
		        i.putExtra("useravatarurl", useravatarurl);
			    startActivity(i);
		    	break;
		    }
		 }
		 return super.onOptionsItemSelected(item);
	  }

	@SuppressLint("NewApi")
	private void initilizeMap() {
        if (googleMap == null) {
            googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
 
            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
            else
            {   				
            	googleMap.setMyLocationEnabled(true);
            	googleMap.setOnMyLocationChangeListener(this);   
            	googleMap.setOnInfoWindowClickListener(this);
            	
            }
        }
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        initilizeMap();
    }
    
    @Override
    public void onMyLocationChange(Location lastKnownLocation) {
        CameraUpdate myLoc = CameraUpdateFactory.newCameraPosition(
                new CameraPosition.Builder().target(new LatLng(lastKnownLocation.getLatitude(),
                        lastKnownLocation.getLongitude())).zoom(15).build());
        googleMap.moveCamera(myLoc);
        localLocation = lastKnownLocation;
        
        new LoadPlaceAsync().execute();

       /* googleMap.clear();
               
    	MarkerOptions marker = new MarkerOptions().position(new LatLng(localLocation.getLatitude(), localLocation.getLongitude()))
    												.title("Đang ở đây")
    												.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
    	googleMap.addMarker(marker);*/
        
        googleMap.setOnMyLocationChangeListener(null);
    }

	@Override
	public void onInfoWindowClick(Marker arg0) {
		// TODO Auto-generated method stub
		String pId = listMarker.get(arg0);
        Intent i = new Intent(NearHereActivity.this, PlaceDetailActivity.class);
        i.putExtra("placeid", pId); 
        i.putExtra("userid",userid);
        i.putExtra("username", username);
        i.putExtra("userdisplayname", userdisplayname);
        i.putExtra("useravatarurl", useravatarurl);
        startActivity(i);
	}
    
    class LoadPlaceAsync extends AsyncTask<String, String, String>
    {
    	PlaceMapLoader placeload = new PlaceMapLoader(Double.toString(localLocation.getLatitude())
    													,Double.toString(localLocation.getLongitude())
    													,"1");
    	@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(NearHereActivity.this);
			pDialog.setMessage("Loading places. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
    	
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
	    	//placeload = new PlaceLoader();
			
			data = placeload.GetPlace();
			return null;
		}
		
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					adapter = new PlaceMapAdapter(NearHereActivity.this, placeload, data);
					//adapter = new PlaceAdapter(ListPlaceActivity.this, placeload);
			        list.setAdapter(adapter);
			        
			        for(final HashMap<String, String> locPlace : data)
			        {
			        	MarkerOptions marker = new MarkerOptions()
			        			.position(new LatLng(Double.parseDouble(locPlace.get("latitude")), Double.parseDouble(locPlace.get("longitude"))))
								.title(locPlace.get("place_name"))
								.snippet(locPlace.get("address") + "-" + locPlace.get("district_name") + "-" + locPlace.get("province_name"))
								.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
			        	
			        		
									//.title(locPlace.get("place_name"))
									//.snippet(locPlace.get("address") + "-" + locPlace.get("district_name") + "-" + locPlace.get("province_name"))
									
			        	Marker mk = googleMap.addMarker(marker);
			        	
			        	listMarker.put(mk,locPlace.get("place_id"));
			        }
				}
			});

		}
    }
		
}
